<?php
/**
 * 文件上传
 * User: hbl
 * Date: 2020/4/29
 * Time: 20:13
 */
namespace App\Lib;

use Illuminate\Support\Facades\Storage;

class UploadLib {

    public static function handle($file, $disk = 'upload_banner') {
        //上传文件最大大小,单位M
        $maxSize = 5;
        //支持的上传图片类型
        $allowed_extensions = ["xls", "png", "jpg", "jpeg"];

        //检查文件是否上传完成
        if ($file->isValid()){
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext),$allowed_extensions)){
                $msg = "请上传".implode(",",$allowed_extensions)."格式文件";
                throw new \Exception($msg);
            }
            //检测图片大小
            if ($file->getClientSize() > $maxSize*1024*1024){
                $msg = "文件大小限制".$maxSize."M";
                throw new \Exception($msg);
            }
        }else{
            $msg = $file->getErrorMessage();
            throw new \Exception($msg);
        }
        $newFile = date('Ymd') . "/" . time()."_".uniqid().".".$file->getClientOriginalExtension();
        Storage::disk($disk)->put($newFile, file_get_contents($file->getRealPath() ));
        return $newFile;
    }
}